package liurong.driver.netty;

import java.util.concurrent.TimeUnit;

import io.netty.util.Recycler;
import io.netty.util.Recycler.Handle;

public class ObjectPoolTest {

	public static void main(String[] args) {

		PoolStudent instance = PoolStudent.getInstance();
		System.out.println("main1:" + instance);
		instance.recycle();
		final PoolStudent instance2 = PoolStudent.getInstance();
		System.out.println("main2:" + instance);

		new Thread(new Runnable() {

			@Override
			public void run() {
				instance2.recycle();
				while (true) {
					PoolStudent instance3 = PoolStudent.getInstance();
					System.out.println("1" + instance2);
					instance3.recycle();
					try {
						TimeUnit.SECONDS.sleep(2);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					PoolStudent instance2 = PoolStudent.getInstance();
					System.out.println("2" + instance2);
					instance2.recycle();
					try {
						TimeUnit.SECONDS.sleep(2);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	public static class PoolStudent {

		private Handle<PoolStudent> handle;

		private static final Recycler<PoolStudent> RECYCLER = new Recycler<PoolStudent>() {

			@Override
			protected PoolStudent newObject(Handle<PoolStudent> handle) {
				return new PoolStudent(handle);
			}
		};

		public PoolStudent(Handle<PoolStudent> handle) {
			this.handle = handle;
		}

		public static PoolStudent getInstance() {
			return RECYCLER.get();
		}

		public void recycle() {
			handle.recycle(this);
		}
	}
}
